<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, initial-scale=0.5, minimum-scale=0.2, maximum-scale=1.0, user-scalable=yes"/>
    <title>BP操作</title>
    <link href="boot.css" rel="stylesheet">
    <script src="common.js"></script>
    <style>
        body, html {
            height: 100%;
            margin: 0;
            padding: 0;
            display: flex;
            flex-direction: column;
        }

        .timer {
            flex: 1;
            background-color: #cccccc;
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 36px; /* 放大字体 */
        }

        .top {
            flex: 7;
            background-color: #f0f0f0;
            display: flex;
            flex-wrap: wrap; /* 让图片可以换行显示 */
            justify-content: space-between;
            align-items: center;
        }

        .image-container {
            width: 100px;
            height: 100px;
            margin: 10px;
            cursor: pointer;
            border: 2px solid transparent;
            transition: border-color 0.3s ease-in-out;
            overflow: hidden; /* 防止图片溢出容器 */
        }

        .image-container img {
            width: 100%; /* 图片宽度填充容器 */
            height: auto; /* 图片高度自适应 */
        }

        .image-container.selected {
            border-color: blue;
        }

        .middle {
            flex: 1;
            background-color: #d3d3d3;
            display: flex;
            justify-content: center;
            align-items: center;
        }

        .decision-button {
            padding: 10px 20px;
            font-size: 32px;
            background-color: #4CAF50;
            color: white;
            border: none;
            cursor: pointer;
            border-radius: 5px;
            text-align: center;
            text-decoration: none;
            display: inline-block;
        }

        .decision-button:hover {
            background-color: #45a049;
        }

        .result-area {
            flex: 2;
            display: flex;
            justify-content: space-between;
            background-size: cover; /* 让背景图片填充整个元素 */
            background-position: center; /* 将背景图片居中 */
            background-repeat: no-repeat; /* 不重复背景图片 */
            background-image: url("https://img.tukuppt.com/bg_grid/01/18/12/zBHdswk4kC.jpg%21/fh/350");
        }

        .team-area {
            flex: 1;
            padding: 10px;
            text-align: center;
        }

        .team-area h2 {
            margin: 0;
        }

        .team-A {
            /*background-color: #ff9999; !* 使用相同颜色区分 A 战队和 B 战队 *!*/
        }

        .team-B {
            /*background-color: #ff9999; !* 使用相同颜色区分 A 战队和 B 战队 *!*/
        }

        .result {
            padding-top: 20px;
            padding-bottom: 20px;
            flex: 2.5;
            display: flex;
            justify-content: space-between;
        }

        .small-result {
            flex: 2;
            display: flex;
            justify-content: space-between;
        }


        .team-image {
            max-width: 100px;
            max-height: 100px;
        }

        .select-image {
            padding: 5px;
            max-width: 50px;
            max-height: 50px;
        }

        .ban-select-image {
            padding: 5px;
            max-width: 50px;
            max-height: 50px;
            opacity: 0.6;
        }

        .left-result {
            flex: 2;
            display: flex;
            justify-content: space-between;
        }

        .right-result {
            flex: 2;
            display: flex;
            justify-content: space-between;
        }

        .center-result {
            flex: 0.5;
            display: flex;
            justify-content: space-between;
        }

        .left-select-result {
            padding: 20px;
        }

        .right-select-result {
            text-align: right;
            padding: 20px;
        }

        .left-ban-result {
            padding: 20px;
        }

        .right-ban-result {
            padding: 20px;
        }

        .overlay {
            background-color: rgba(77, 59, 59, 0.7); /* 使用 rgba 颜色表示法，最后一个参数设置透明度 */
            z-index: 999; /* 确保蒙板在最顶层 */
        }

        .alert {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            padding: 10px 20px;
            background-color: #f8d7da; /* 设置弹窗的背景颜色 */
            border: 1px solid #721c24; /* 设置弹窗的边框 */
            border-radius: 5px; /* 设置弹窗的边框圆角 */
            color: #721c24; /* 设置弹窗的文字颜色 */
            z-index: 9999; /* 设置弹窗的堆叠顺序，确保弹窗在其他元素之上 */
        }

        .alert-success {
            background-color: #d4edda; /* 设置成功提示的背景颜色 */
            border-color: #155724; /* 设置成功提示的边框颜色 */
            color: #155724; /* 设置成功提示的文字颜色 */
        }

        .left-finish-team {
            flex: 1;
            display: flex;
            flex-direction: column; /* 垂直排列 */
            align-items: center; /* 在主轴上居中对齐 */
            justify-content: center; /* 在交叉轴上居中对齐 */
        }

        .imageContainer {
            /*height: 100%;*/
            /*background-color: white;*/
            flex: 2;
            display: flex;
            justify-content: center;
            flex-wrap: wrap;
        }

        .right-finish-team {
            flex: 1;
            display: flex;
            flex-direction: column; /* 垂直排列 */
            align-items: center; /* 在主轴上居中对齐 */
            justify-content: center; /* 在交叉轴上居中对齐 */
        }

        .popup-container_waiting_join {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background-color: #fff;
            padding: 30px; /* 增加 padding 大小 */
            padding-left: 50px; /* 增加 padding 大小 */
            padding-right: 50px; /* 增加 padding 大小 */
            border-radius: 10px;
            box-shadow: 0 0 20px rgba(0, 0, 0, 0.2); /* 增加阴影大小 */
            text-align: center;
            z-index: 999; /* 设置 z-index，确保弹窗在最上层 */
        }

        .confirm_decision {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background-color: #fff;
            padding: 30px; /* 增加 padding 大小 */
            padding-left: 90px; /* 增加 padding 大小 */
            padding-right: 90px; /* 增加 padding 大小 */
            border-radius: 10px;
            box-shadow: 0 0 20px rgba(0, 0, 0, 0.2); /* 增加阴影大小 */
            text-align: center;
            z-index: 999; /* 设置 z-index，确保弹窗在最上层 */
        }

        button {
            padding: 10px 20px;
            margin: 0 30px;
            font-size: 24px;
            border: none;
            border-radius: 5px;
            background-color: #007bff;
            color: #fff;
            cursor: pointer;
            transition: background-color 0.3s;
        }

        button:hover {
            background-color: #0056b3;
        }
    </style>
</head>
<body>
<div class="timer" id="timer"></div>
<div class="top">
    <div id="left-finish-team" class="left-finish-team">
    </div>
    <div id="imageContainer" class="imageContainer">
    </div>
    <div id="right-finish-team" class="right-finish-team">
    </div>
    <!-- 图片将在此动态生成 -->
</div>
<div class="popup-container_waiting_join" id="popup_waiting_join" style="display: none;">
    <p>本次BP已结束，感谢您的配合，谢谢~</p>
    <button onclick="backToNavigation()">好的</button>
</div>
<div class="confirm_decision" id="confirm_decision" style="display: none;">
    <h2>请确认您的选择：</h2>
    <button onclick="decision()">确认</button>
    <button onclick="cancelConfirmDecision()">取消</button>
</div>
<div class="middle">
    <!-- 决策区域 -->
    <button id="decision-button" class="decision-button" onclick="confirmDecision()"></button>
</div>
<div class="result-area">
    <div class="team-area team-A">
        <h2 id="aUsername" style="color: white"></h2>
        <img id="aImage" alt="Team A Image" class="team-image">
    </div>
    <div class="result">
        <div class="small-result overlay">
            <div class="left-result">
                <div id="left-select-result" class="left-select-result">
                    <h3 style="color: white">选用</h3>
                </div>
                <div id="left-ban-result" class="left-ban-result">
                    <h3 style="color: red;text-align: center">禁用</h3>
                </div>
            </div>
            <div class="center-result">
            </div>
            <div class="right-result">
                <div id="right-ban-result" class="right-ban-result">
                    <h3 style="color: red;text-align: center">禁用</h3>
                </div>
                <div id="right-select-result" class="right-select-result">
                    <h3 style="text-align: right;color: white">选用</h3>
                </div>
            </div>
        </div>
    </div>
    <div class="team-area team-B">
        <h2 id="bUsername" style="color: white"></h2>
        <img id="bImage" alt="Team B Image" class="team-image">
    </div>
</div>
<audio id="myAudio">
    <source src="music.wav" type="audio/wav">
</audio>

<script>
    if (sessionStorage.getItem("username") === null || sessionStorage.getItem("username") === "undefined") {
        window.location.href = '/bp/login.html'; // 替换为你想要跳转的页面的URL
    }

    if (localStorage.getItem("roomId") === null || localStorage.getItem("roomId") === "undefined") {
        window.location.href = '/bp/navigation.html'; // 替换为你想要跳转的页面的URL
    }

    function backToNavigation() {
        window.location.href = '/bp/navigation.html'; // 替换为你想要跳转的页面的URL
    }

    function selectImage(element) {
        // 获取所有已选中的图片
        const selectedImages = document.querySelectorAll('.image-container.selected');
        // 如果条件满足，并且已选中的图片数量小于 2，就添加当前图片的选中状态
        // 否则，如果条件不满足，或者已选中的图片数量大于等于 2，就取消所有已选中的图片的选中状态，并单选当前图片
        selectedImages.forEach(img => img.classList.remove('selected'));
        element.classList.add('selected');
    }


    // 设置倒计时
    const timerElement = document.getElementById("timer");

    var timeout;
    var aindex = 1;
    var bindex = 1;

    var a1index = 1;
    var b2index = 1;

    function countdown() {
        // 获取当前时间戳（单位：秒）
        // 更新页面上显示的倒计时
        if (timeout <= 0 || localStorage.getItem("stage") === "结束") {
            timerElement.textContent = localStorage.getItem("stage");
        } else {
            timerElement.textContent = localStorage.getItem("stage")
                + " " + timeout + "秒";
            if (timeout < 10 && !localStorage.getItem("stage").includes("等待")) {
                timerElement.style.fontSize = "42px"; // 增大字体
                timerElement.style.fontWeight = "bold"; // 变粗字体
            } else {
                timerElement.style.fontSize = ""; // 恢复默认字体大小
                timerElement.style.fontWeight = ""; // 恢复默认字体粗细
            }
        }
    }

    function n2h(index) {
        if (index === 1) {
            return "一"
        }
        if (index === 2) {
            return "二"
        }
        if (index === 3) {
            return "三"
        }
    }


    var socket = null; // 声明 socket 变量，用于存储 WebSocket 对象
    var socketUrl = "ws://" + ip + ":8081/ws"; // 替换为实际的 WebSocket 服务器地址
    var reconnectTimer = null; // 重新连接的定时器

    // 在页面加载时执行此函数
    connect();

    function connect() {
        if (sessionStorage.getItem("username") === null || sessionStorage.getItem("username") === "undefined") {
            window.location.href = '/bp/login.html'; // 替换为你想要跳转的页面的URL
        }
        if (localStorage.getItem("roomId") === null || localStorage.getItem("roomId") === "undefined") {
            window.location.href = '/bp/navigation.html'; // 替换为你想要跳转的页面的URL
        }
        // 创建 WebSocket 连接
        socket = new WebSocket(socketUrl);

        // 连接成功时的回调函数
        socket.onopen = function (event) {
            cancelReconnect();
            login();
            // console.log("WebSocket 连接已建立.");
            // 连接成功后取消重新连接的定时器
        };

        // 收到消息时的回调函数
        socket.onmessage = function (event) {
            handle(event);
        };

        // 监听连接关闭事件
        socket.onclose = function (event) {
            // 如果连接仍然关闭，启动重新连接的定时器
            startReconnect();
        };
    }

    // 开始重新连接的定时器
    function startReconnect() {
        if (!reconnectTimer) {
            reconnectTimer = setInterval(connect, 3000); // 每秒尝试重新连接
        }
    }

    // 取消重新连接的定时器
    function cancelReconnect() {
        if (reconnectTimer) {
            clearInterval(reconnectTimer);
            reconnectTimer = null;
        }
    }


    function handle(event) {
        var message = JSON.parse(event.data); // 将收到的消息解析为 JSON 对象
        // console.log(message);
        var action = message.action; // 获取消息中的 action 属性
        // 根据 action 属性分发处理逻辑
        switch (action) {
            case "LOGIN":
                start();
                break;
            case "SELECT":
                playMusic()
                handleSelect(message.content);
                refresh(message.content);
                var index2 = localStorage.getItem("role") === "A" ? aindex : bindex;
                var index1 = localStorage.getItem("role") === "A" ? a1index : b2index;
                if (localStorage.getItem("stageName") === "第一阶段") {
                    localStorage.setItem("stage", "请您选择第" + n2h(index1) + "支球队")
                } else {
                    localStorage.setItem("stage", "请您选择第" + n2h(index2) + "局使用的球队")
                }
                break;
            case "WAIT":
                playMusic()
                handleWait();
                refresh(message.content);
                const m = "正在等待对手" + (message.extra === "SELECT" ? "选择" : "禁用");
                localStorage.setItem("stage", m);
                break;
            case "BAN":
                playMusic()
                handleBan();
                refresh(message.content);
                localStorage.setItem("stage", "请您禁用一支球队")
                break;
            case "FINISH_ONE":
                playMusic()
                refresh(message.content);
                handleFinish()
                localStorage.setItem("stage", "第一阶段BP结束")
                break;
            case "FINISH_TWO":
                playMusic()
                refresh(message.content);
                handleFinish()
                localStorage.setItem("stage", "结束")
                localStorage.removeItem("roomId")
                const block = document.getElementById('popup_waiting_join');
                block.style.display = 'block';
                break;
            case "TIME":
                timeout = message.content;
                break;
            case "KICK":
                showAlert('账号在其他地方被登录', 'alert-danger');
                socket.close()
                cancelReconnect();
                setInterval(logout, 3000);
                break;
            default:
                // console.log("Unknown action:", action);
                break;
        }
    }

    function playMusic() {
        document.getElementById('myAudio').play();
    }

    function logout() {
        // 点击“退出账号”按钮后的操作，例如跳转到退出登录页面
        sessionStorage.removeItem("username")
        window.location.href = '/bp/login.html'; // 替换为实际的退出登录页面URL
    }

    function getCurrentUserRole(users) {
        // 这里可以根据具体逻辑来确定当前用户的角色，比如根据用户名查找用户信息等
        // 这里简单地返回第一个用户的角色作为当前用户的角色
        return users[0].username === sessionStorage.getItem("username") ? users[0].role : users[1].role;
    }

    function refresh(message) {
        cancelConfirmDecision()
        var data = JSON.parse(message);
        var canSelectTeam = data.canSelectTeam;
        var aSelectTeam = data.aSelectTeam;
        var bSelectTeam = data.bSelectTeam;
        var aBanTeam = data.aBanTeam;
        var bBanTeam = data.bBanTeam;
        var aUser = data.aUser;
        var bUser = data.bUser;
        localStorage.setItem("role", getCurrentUserRole(data.users))
        localStorage.setItem("stageName", data.stageName);
        refreshAUser(aUser)
        refreshBUser(bUser)
        if (data.stageName === "第一阶段") {
            refreshCanSelectTeam(canSelectTeam)
        } else {
            if (aUser.username === sessionStorage.getItem("username")) {
                canSelectTeam = data.aCanSelectTeam;
            } else {
                canSelectTeam = data.bCanSelectTeam;
            }
            refreshCanSelectTeam(canSelectTeam)
            var aFinalSelectTeam = data.aFinalSelectTeam;
            var bFinalSelectTeam = data.bFinalSelectTeam;
            refreshAFinishSelectTeam(aFinalSelectTeam)
            refreshBFinishSelectTeam(bFinalSelectTeam)
        }
        refreshASelectTeam(aSelectTeam)
        refreshBSelectTeam(bSelectTeam)
        refreshABanTeam(aBanTeam)
        refreshBBanTeam(bBanTeam)
    }

    function confirmDecision() {
        var block = document.getElementById('confirm_decision')
        block.style.display = 'block';
    }

    function cancelConfirmDecision() {
        var block = document.getElementById('confirm_decision')
        block.style.display = 'none';
    }

    function decision() {
        const decisionButton = document.getElementById("decision-button");
        decisionButton.style.display = "none";
        var block = document.getElementById('confirm_decision')
        block.style.display = 'none';

        var firstSelectedImageId = "skip"
        if (decisionButton.textContent !== "跳过") {
            const selectedImages = document.querySelectorAll('.image-container.selected');
            firstSelectedImageId = selectedImages[0].querySelector('img').getAttribute('id');
        }

        var request = {
            action: "DECISION",
            roomId: localStorage.getItem("roomId"),
            content: firstSelectedImageId
        }

        var jsonString = JSON.stringify(request);
        sendMessage(jsonString);
        if (decisionButton.textContent === "跳过") {
            decisionButton.style.display = "none";
            localStorage.setItem("stage", "正在等待对手")
        }

    }

    function refreshAUser(aUser) {
        const name = document.getElementById("aUsername");
        const aImage = document.getElementById("aImage");
        name.textContent = aUser.username
        aImage.src = aUser.image
    }

    function refreshBUser(bUser) {
        const name = document.getElementById("bUsername");
        const bImage = document.getElementById("bImage");
        name.textContent = bUser.username
        bImage.src = bUser.image
    }

    function refreshASelectTeam(aSelectTeam) {
        const leftSelectResult = document.getElementById("left-select-result");
        const elements = document.querySelectorAll(".left-select-result-image");
        elements.forEach(function (element) {
            element.remove();
        });
        var i = 1;
        aSelectTeam.forEach((team, index) => {
            const img = document.createElement("img");
            img.src = team.image;
            img.id = team.name;
            img.alt = "Image";
            i++;
            a1index = i;
            img.className = "select-image left-select-result-image";
            leftSelectResult.appendChild(img);
        });
    }

    function refreshBSelectTeam(bSelectTeam) {
        const leftSelectResult = document.getElementById("right-select-result");
        const elements = document.querySelectorAll(".right-select-result-image");
        elements.forEach(function (element) {
            element.remove();
        });
        var i = 1;
        for (let index = bSelectTeam.length - 1; index >= 0; index--) {
            const team = bSelectTeam[index];
            const img = document.createElement("img");
            img.src = team.image;
            img.id = team.name;
            img.alt = "Image";
            i++;
            b2index = i;
            img.className = "select-image right-select-result-image";
            leftSelectResult.appendChild(img);
        }
    }

    function refreshABanTeam(aBanTeam) {
        const aBanResult = document.getElementById("left-ban-result");
        const elements = document.querySelectorAll(".left-ban-result-image");
        elements.forEach(function (element) {
            element.remove();
        });
        aBanTeam.forEach((team, index) => {
            const img = document.createElement("img");
            img.src = team.image;
            img.id = team.name;
            img.alt = "Image";
            img.className = "ban-select-image left-ban-result-image";
            aBanResult.appendChild(img);
        });
    }

    function refreshBBanTeam(bBanTeam) {
        const aBanResult = document.getElementById("right-ban-result");
        const elements = document.querySelectorAll(".right-ban-result-image");
        elements.forEach(function (element) {
            element.remove();
        });
        bBanTeam.forEach((team, index) => {
            const img = document.createElement("img");
            img.src = team.image;
            img.id = team.name;
            img.alt = "Image";
            img.className = "ban-select-image right-ban-result-image";
            aBanResult.appendChild(img);
        });
    }

    function refreshAFinishSelectTeam(aFinishSelectTeam) {
        const imageContainer = document.getElementById("left-finish-team");
        while (imageContainer.firstChild) {
            imageContainer.removeChild(imageContainer.firstChild);
        }
        var i = 1;
        // 根据图片 URL 列表动态生成图片
        aFinishSelectTeam.forEach((team, index) => {
            const box = document.createElement("div");
            box.style.display = "flex"
            const div = document.createElement("div");
            div.className = "image-container";
            const img = document.createElement("img");
            img.src = team.image;
            img.id = team.name;
            img.alt = "Image";
            const text = document.createElement("h2");
            text.innerText = "第" + i + "局"
            text.style.alignSelf = "center"
            i++;
            aindex = i;
            div.appendChild(img);
            box.appendChild(text);
            box.appendChild(div)
            imageContainer.appendChild(box);
        });
    }

    function refreshBFinishSelectTeam(bFinishSelectTeam) {
        const imageContainer = document.getElementById("right-finish-team");
        while (imageContainer.firstChild) {
            imageContainer.removeChild(imageContainer.firstChild);
        }
        var i = 1;
        // 根据图片 URL 列表动态生成图片
        bFinishSelectTeam.forEach((team, index) => {
            const box = document.createElement("div");
            box.style.display = "flex"
            const div = document.createElement("div");
            div.className = "image-container";
            const img = document.createElement("img");
            img.src = team.image;
            img.id = team.name;
            img.alt = "Image";
            const text = document.createElement("h2");
            text.innerText = "第" + i + "局"
            text.style.alignSelf = "center"
            i++;
            bindex = i;
            div.appendChild(img);
            box.appendChild(div)
            box.appendChild(text);
            imageContainer.appendChild(box);
        });
    }

    function refreshCanSelectTeam(canSelectTeam) {
        const imageContainer = document.getElementById("imageContainer");
        while (imageContainer.firstChild) {
            imageContainer.removeChild(imageContainer.firstChild);
        }
        // 根据图片 URL 列表动态生成图片
        canSelectTeam.forEach((team, index) => {
            const div = document.createElement("div");
            div.className = "image-container";
            div.onclick = function () {
                selectImage(this);
            };

            const img = document.createElement("img");
            img.src = team.image;
            img.id = team.name;
            img.alt = "Image";

            div.appendChild(img);
            imageContainer.appendChild(div);

            // 默认选中第一个图片
            if (index === 0) {
                div.classList.add('selected');
            }
        });
    }

    // 发送消息的函数
    function sendMessage(message) {
        socket.send(message);
    }

    function login() {
        // 创建房间的逻辑
        var loginRequest = {
            action: "LOGIN",
            content: sessionStorage.getItem('username'),
            otherMessage: "BP页面登陆"
        };
        var jsonString = JSON.stringify(loginRequest);
        sendMessage(jsonString);
    }

    function start() {
        var request = {
            action: "START",
            roomId: localStorage.getItem('roomId'),
        };
        var jsonString = JSON.stringify(request);
        sendMessage(jsonString);
    }

    function handleSelect(content) {
        // console.log("处理选择的逻辑:", content);
        const decisionButton = document.getElementById("decision-button");
        decisionButton.style.display = "block";
        decisionButton.textContent = "选用"
    }

    function handleWait() {
        const decisionButton = document.getElementById("decision-button");
        decisionButton.style.display = "none";
    }

    function handleFinish() {
        const decisionButton = document.getElementById("decision-button");
        if (localStorage.getItem("stageName") === "第一阶段") {
            decisionButton.style.display = "block";
            decisionButton.textContent = "跳过"
        } else {
            decisionButton.style.display = "none";
        }
    }

    function handleBan() {
        // console.log("处理禁止的逻辑:", content);
        const decisionButton = document.getElementById("decision-button");
        decisionButton.style.display = "block";
        decisionButton.textContent = "禁用"
    }

    function showAlert(message, className) {
        const alertDiv = document.createElement('div');
        alertDiv.className = `alert ${className} mt-4`;
        alertDiv.textContent = message;
        // 居中显示
        alertDiv.style.position = 'fixed';
        alertDiv.style.top = '50%';
        alertDiv.style.left = '50%';
        alertDiv.style.transform = 'translate(-50%, -50%)';

        document.body.appendChild(alertDiv);


        // 3秒后自动关闭弹窗
        setTimeout(() => {
            alertDiv.remove();
        }, 3000);
    }

    setInterval(countdown, 1000);
</script>
</body>
</html>
